class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        HashMap<String, Integer> map = new HashMap<>();
        for(int i = 0; i <words.length; i++){
            map.put(words[i], map.getOrDefault(words[i], 0) + 1); //如果不存在默认为0, 存在则 + 1个数
        }
        List<String> ret = new LinkedList<>(map.keySet()); //构造Key的集合
        Collections.sort(ret, (w1, w2) ->{
            Integer cnt1 = map.get(w1);
            Integer cnt2 = map.get(w2);
            if(cnt1 != cnt2){
                return cnt2.compareTo(cnt1);
            }else{
                return w1.compareTo(w2);
            }
        });
        return ret.subList(0, k);
    }
}
